from collections import namedtuple

from flask import current_app, g, request
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer \
    as Serializer, BadSignature, SignatureExpired
from flask_app.common.result import true_return, false_return


__author__ = '叶伟伟'

auth = HTTPTokenAuth(scheme='Bearer')
User = namedtuple('User', ['uid', 'username', 'role_id'])

@auth.verify_token
def verify_token(token):
    """
    请求时带上参数头
    headers['Authorization'] = 'Bearer ' + token
    """
    g.user = None
    user =  verify_auth_token(token)
    if user:
        g.user = user
        return True
    else:
        return False

@auth.error_handler
def unauthorized():
    return false_return('未进行token鉴权')

def verify_auth_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
        uid = data['uid']
        username = data['username']
        role_id = data['role_id']
    except BadSignature:
        return False
    except SignatureExpired:
        return False
    except KeyError:
        return False
    # request 视图函数
    # allow = is_in_scope(scope, request.endpoint)
    # if not allow:
    #     raise Forbidden()
    return User(uid, username, role_id)
